import zhCN from '../locales/zh-CN';

type NestedKeyOf<T> = {
  [K in keyof T]: T[K] extends object
    ? `${K extends string ? K : never}.${NestedKeyOf<T[K]> extends string ? NestedKeyOf<T[K]> : never}`
    : K extends string ? K : never;
}[keyof T];

type LocaleKey = NestedKeyOf<typeof zhCN>;

class I18n {
  private locale: typeof zhCN;

  constructor() {
    this.locale = zhCN;
  }

  t(key: LocaleKey, params: Record<string, string | number> = {}): string {
    const keys = key.split('.');
    let value: any = this.locale;

    for (const k of keys) {
      value = value[k];
      if (value === undefined) {
        console.warn(`Translation key not found: ${key}`);
        return key;
      }
    }

    if (typeof value !== 'string') {
      console.warn(`Translation value is not a string: ${key}`);
      return key;
    }

    // Replace parameters in the string
    return value.replace(/{(\w+)}/g, (_, k) => {
      return params[k]?.toString() ?? `{${k}}`;
    });
  }
}

export const i18n = new I18n();